package com.bifrost.initializer;

import com.bifrost.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Author by yanxiaobo
 * Date on 2018/4/12$.
 */
@Component("permissionInitializer")
@Slf4j
public class PermissionInitializer implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent() == null){//root application context 没有parent.
            ApplicationContext applicationContext = event.getApplicationContext();
            AbstractShiroFilter shiroFilter = (AbstractShiroFilter) applicationContext.getBean("shiroFilter");
            PathMatchingFilterChainResolver resolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            FilterChainManager manager = resolver.getFilterChainManager();

            PermissionService permissionService = (PermissionService) applicationContext.getBean("permissionService");
            try {
                Map<String, String> chains = new LinkedHashMap<>();
                chains.putAll(permissionService.buildFilterChainDefinitionMap());
                chains.put("/admin/login", "anon");
                //swagger 配置
                chains.put("/public/**", "anon");
                chains.put("/webjars/**", "anon");
                chains.put("/api/**", "anon");
                chains.put("/swagger**", "anon");
                chains.put("/v2/api-docs", "anon");
                chains.put("/swagger-resources/configuration/ui", "anon");
                chains.put("/login.html", "anon");
                chains.put("/captcha.jpg", "anon");
                chains.put("/**", "anon");

                //build up the chains:
                if (!CollectionUtils.isEmpty(chains)) {
                    for (Map.Entry<String, String> entry : chains.entrySet()) {
                        String url = entry.getKey();
                        String chainDefinition = entry.getValue();
                        manager.createChain(url, chainDefinition);
                    }
                }

            } catch(Exception e) {
                log.warn("初始化权限数据出错:{}",e);
                return;
            }
            log.info("初始化权限数据成功");
        }
    }
}
